package dolphin.mt521.cam.ac.uk;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.Environment;
import android.util.Log;

public class Dolphin {
    
    void run () {
        try {
            ServerSocket servSock = new ServerSocket(3574);
            Socket channel = servSock.accept();
            
            OutputStream out = channel.getOutputStream();
            PrintStream pStream = new PrintStream(out);
            
            InputStream in = channel.getInputStream();
            BufferedInputStream bin = new BufferedInputStream(in);
            
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int bytesRead = 1;  //initial value is meaningless, needs to be greater than 0 for loop condition
            while ((bytesRead>0)) {
                bytesRead=bin.read(buffer,0,1024);
                if (bytesRead>0) {
                    baos.write(buffer,0,1024);
                }
            }
            encode(baos.toByteArray());
            pStream.println("Encoding complete.");
            
        } catch (IOException e) {
            Log.e("Dolphin","Server Socket failed to initialise.");
        }
    }

    public static void encode(byte[] bData) {
        Encode.encode(bData);
    }
    
    public static void encodePreset() {
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(baseDir+"/encode.txt");
        byte[] bData = Encode.convertToBytes(file);
        Encode.encode(bData);
    }
    
    public static void decode() {
        byte[] bTone = Microphone.mic();
        Decode.decodeOld(bTone);
    }
    
    public static void decodeHalf() {
        byte[] bTone = Microphone.mic();
        Decode.decode(bTone);
    }
    

}